import imaplib
import email
from email.header import decode_header
import csv
import getpass

# --- 配置信息 ---
# 邮箱服务器地址
IMAP_SERVER = "imap.163.com"
# 您的邮箱地址
EMAIL_ACCOUNT = "justforted@163.com"
# 使用 getpass 安全地输入授权码，而不是硬编码在脚本里
# 注意：这里输入的是授权码，不是你的邮箱登录密码！
PASSWORD = "HLykuQC6dsZVb7js"
# 目标联系人邮箱
TARGET_CONTACT = "contact@alphaxiv.org"
# 输出的CSV文件名
CSV_FILENAME = "emails_with_alphaxiv.csv"


def clean_header(header):
    """解码邮件头 (主题, 发件人, 收件人)"""
    if header is None:
        return ""
    decoded_parts = decode_header(header)
    parts = []
    for part, charset in decoded_parts:
        if isinstance(part, bytes):
            try:
                parts.append(part.decode(charset or "utf-8", errors="ignore"))
            except (UnicodeDecodeError, LookupError):
                parts.append(part.decode("gb18030", errors="ignore"))
        else:
            parts.append(part)
    return "".join(parts)


def get_email_body(msg):
    """获取邮件正文内容"""
    if msg.is_multipart():
        for part in msg.walk():
            content_type = part.get_content_type()
            content_disposition = str(part.get("Content-Disposition"))

            if "text/plain" in content_type and "attachment" not in content_disposition:
                try:
                    charset = part.get_content_charset() or "utf-8"
                    return part.get_payload(decode=True).decode(charset, "ignore")
                except (UnicodeDecodeError, LookupError):
                    return part.get_payload(decode=True).decode("gb18030", "ignore")
    else:
        try:
            charset = msg.get_content_charset() or "utf-8"
            return msg.get_payload(decode=True).decode(charset, "ignore")
        except (UnicodeDecodeError, LookupError):
            return msg.get_payload(decode=True).decode("gb18030", "ignore")
    return ""


def fetch_emails():
    """连接邮箱，获取邮件并保存到CSV"""
    # 连接到IMAP服务器
    mail = imaplib.IMAP4_SSL(IMAP_SERVER)
    try:
        # 登录
        mail.login(EMAIL_ACCOUNT, PASSWORD)
        print("登录成功！")

        # 选择收件箱
        mail.select("inbox")

        # 构建搜索条件：发件人是目标 或 收件人是目标
        search_criteria = f'(OR (FROM "{TARGET_CONTACT}") (TO "{TARGET_CONTACT}"))'

        # 搜索邮件
        status, messages = mail.search(None, search_criteria)
        email_ids = messages[0].split()

        if not email_ids:
            print(f"没有找到与 {TARGET_CONTACT} 的往来邮件。")
            return

        print(f"找到 {len(email_ids)} 封相关邮件，正在处理...")

        # 打开CSV文件准备写入
        with open(CSV_FILENAME, "w", newline="", encoding="utf-8-sig") as csvfile:
            writer = csv.writer(csvfile)
            # 写入表头
            writer.writerow(["Date", "From", "To", "Subject", "Body"])

            # 遍历所有邮件ID
            for email_id in reversed(email_ids):  # 从最新的开始
                status, msg_data = mail.fetch(email_id, "(RFC822)")
                raw_email = msg_data[0][1]
                msg = email.message_from_bytes(raw_email)

                # 提取信息
                date_str = clean_header(msg["Date"])
                from_str = clean_header(msg["From"])
                to_str = clean_header(msg["To"])
                subject_str = clean_header(msg["Subject"])
                body = (
                    get_email_body(msg).strip().replace("\r\n", " ").replace("\n", " ")
                )

                # 写入CSV行
                writer.writerow([date_str, from_str, to_str, subject_str, body])

        print(f"所有邮件已成功保存到 {CSV_FILENAME}")

    except imaplib.IMAP4.error as e:
        print(f"登录失败或发生错误: {e}")
        print("请检查您的邮箱地址和授权码是否正确，以及是否开启了IMAP服务。")
    finally:
        # 关闭连接
        mail.logout()


# --- 运行脚本 ---
if __name__ == "__main__":
    fetch_emails()
